/*
 * URLConnection.cpp
 *
 *  Created on: 2010-6-19
 *      Author: guobc
 */

#include "URLConnection.h"

namespace HA {

int URLConnection::connect() {
	m_socket.socketConnect(mUrl.getHostName().c_str(), 80);
	return m_socket.good() ? 1 : -1;
}

void URLConnection::close() {
	m_socket.socketClose();
}

void URLConnection::download(string& content) {
	if (m_socket.good()) {
		sendRequests();
		string data;
		int length = 129;
		char buffer[length];
		memset(buffer, 0, length);
		m_socket.socketRead(buffer, length - 1);
		while (m_socket.good() && strlen(buffer) != 0) {
			data.append(buffer);
			memset(buffer, 0, length);
			m_socket.socketRead(buffer, length - 1);
		}

		string::size_type pos = data.find_first_of('<');
		if (pos != string::npos) {
			data = data.substr(pos);
			content.append(data);
			data.clear();
		}
	}
}

void URLConnection::sendRequests() {
	m_socket.socketSend("GET / HTTP/1.1%c", 10);
	m_socket.socketSend("HOST: %s%c", mUrl.getHostName().c_str(), 10);
	m_socket.socketSend("User-Agent: HTMLAnalyzer%c", 10);
	m_socket.socketSend(
			"Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2%c",
			10);
	m_socket.socketSend("Connection: keep-alive%c", 10);
	m_socket.socketSend("%c", 10);
}

}
